/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.service.push;

import com.je.common.base.service.MetaRbacService;
import com.je.common.base.service.MetaService;
import com.je.message.vo.Message;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * AbstractPlatformPushService
 *
 * @author wangmm@ketr.com.cn
 * @date 2020/5/09
 */
public abstract class AbstractPlatformPushService implements PlatformPushService {

    /**
     * SpEL解析器
     */
    private static final SpelExpressionParser PARSER = new SpelExpressionParser();

    /**
     * 匹配示例: #{bean['USER_NAME']}
     */
    private static final TemplateParserContext TEMPLATE = new TemplateParserContext();

    /**
     * 日志
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected MetaService metaService;

    @Autowired
    protected MetaRbacService metaRbacService;

    /**
     * 获取匹配的字符串
     * <p>
     * 将 message 对象作为root节点，遍历 message.params 的key并加入到上下文中
     * 使用方式如下:
     * 1.业务数据调用 #{bean['USER_NAME']}
     * 2.拓展参数调用 #{params['config']}，#{#config}
     *
     * @param context  上下文对象
     * @param message  根节点
     * @param template 模板内容
     * @return java.lang.String
     */
    private static String matchParameter(EvaluationContext context, Message message, String template) {
        if (StringUtils.isBlank(template)) {
            return template;
        }
        //示例 "#{#person.name!=null?'他的名字叫'+#person.name+'。':'不知道名字。'}"
        return PARSER.parseExpression(template, TEMPLATE).getValue(context, message, String.class);
    }

    /**
     * 替换消息中的变量
     *
     * @param message 消息对象
     */
    public static void format(Message message) {
        Map<String, Object> bean = message.getBean();
        Map<String, Object> params = message.getParams();
        if (bean == null && params == null) {
            return;
        }

        //添加变量
        EvaluationContext context = new StandardEvaluationContext();
        //params添加到全局变量
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            context.setVariable(entry.getKey(), entry.getValue());
        }

        message.setTitle(matchParameter(context, message, message.getTitle()));
        message.setContent(matchParameter(context, message, message.getContent()));
        message.setButtonText(matchParameter(context, message, message.getButtonText()));
        message.setButtonAction(matchParameter(context, message, message.getButtonAction()));
    }
}